package com.mouse.hxsj.view;

import com.mouse.damo.micro.Com;
import com.mouse.damo.micro.Press;
import com.mouse.damo.micro.Sleep;
import com.mouse.hxsj.constants.ComPool;
import com.mouse.hxsj.entity.common.Hwnd;
import com.mouse.hxsj.entity.enums.BaseKey;
import com.mouse.hxsj.util.ViewGet;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

@Component
public class AutoKeyFrm extends JInternalFrame {
    private JTable table;
    private JTextField textField_interval;
    private JComboBox<Hwnd> comboBox_hwnd;

    private JComboBox<BaseKey> comboBox_key;
    private List<BaseData> baseDataList = new ArrayList<>();
    private JButton button_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AutoKeyFrm frame = new AutoKeyFrm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public AutoKeyFrm() {
        setClosable(true);
        setIconifiable(true);

        setTitle("自动按键");
        setBounds(20, 20, 607, 390);

        JScrollPane scrollPane = new JScrollPane();

        JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(null, "\u65B0\u589E", TitledBorder.LEADING, TitledBorder.TOP, null, null));

        JButton btnNewButton = new JButton("清空列表");
        btnNewButton.addActionListener(e -> {
            if(button_1.getText().equals("停止")){
                JOptionPane.showMessageDialog(null, "请先停止");
                return;
            }
            baseDataList.clear();
            initData();
        });
        JButton button = new JButton("搜索");
        button.addActionListener(e -> initData());
        JButton btnNewButton_1 = new JButton("新增");
        btnNewButton_1.addActionListener(e -> add());
        button_1 = new JButton("启动");
        button_1.addActionListener(e -> start());
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                        .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
                                                .addContainerGap()
                                                .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
                                                        .addComponent(panel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
                                                        .addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)))
                                        .addGroup(groupLayout.createSequentialGroup()
                                                .addGap(58)
                                                .addComponent(btnNewButton)
                                                .addGap(33)
                                                .addComponent(button)
                                                .addGap(26)
                                                .addComponent(btnNewButton_1)
                                                .addGap(33)
                                                .addComponent(button_1)))
                                .addContainerGap())
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGap(12)
                                .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 175, GroupLayout.PREFERRED_SIZE)
                                .addGap(18)
                                .addComponent(panel, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(btnNewButton)
                                        .addComponent(button)
                                        .addComponent(btnNewButton_1)
                                        .addComponent(button_1))
                                .addContainerGap(31, Short.MAX_VALUE))
        );

        JLabel label = new JLabel("句柄");

        comboBox_hwnd = new JComboBox();
        JLabel label_1 = new JLabel("按键");

        comboBox_key = new JComboBox();

        JLabel label_interval = new JLabel("间隔");

        textField_interval = new JTextField();
        textField_interval.setColumns(10);
        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
                gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                                .addComponent(label)
                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                .addComponent(comboBox_hwnd, GroupLayout.PREFERRED_SIZE, 141, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                .addComponent(label_1)
                                .addGap(18)
                                .addComponent(comboBox_key, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                .addComponent(label_interval)
                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                .addComponent(textField_interval, GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                                .addContainerGap())
        );
        gl_panel.setVerticalGroup(
                gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                                .addGap(22)
                                .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(label)
                                        .addComponent(comboBox_hwnd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(label_1)
                                        .addComponent(comboBox_key, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(label_interval)
                                        .addComponent(textField_interval, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(33, Short.MAX_VALUE))
        );
        panel.setLayout(gl_panel);

        table = new JTable();
        table.setModel(new DefaultTableModel(
                new Object[][]{
                },
                new String[]{
                        "\u53E5\u67C4", "\u6309\u952E", "\u95F4\u9694(s)"
                }
        ));
        scrollPane.setViewportView(table);
        getContentPane().setLayout(groupLayout);

    }

    private static List<Thread> threadList = new ArrayList<>();

    private void start() {
        String text = button_1.getText();
        if (text.equals("停止")) {
            button_1.setText("开启");
            for (Thread thread : threadList) {
                thread.stop();
            }
            threadList.clear();
            return;
        }
        if(baseDataList.size()==0){
            JOptionPane.showMessageDialog(null, "请添加按键");
            return;
        }
        button_1.setText("停止");
        for (BaseData baseData : baseDataList) {
            Thread thread = new Thread(() -> {
                while (true) {
                    Com thisCom = null;
                    for (Com com : ComPool.getComList()) {
                        Integer hwnd = baseData.getHwnd();
                        if (hwnd.equals(com.getHwnd())) {
                            thisCom = com;
                            break;
                        }
                    }
                    if (thisCom == null) return;
                    Press press = new Press(thisCom);
                    press.keyPress(baseData.getKeyNum());
                    Integer interval = baseData.getInterval();
                    if (interval == null || interval <= 0) interval = 1;
                    Sleep.sleep(interval);
                }

            });
            thread.start();
            threadList.add(thread);
        }
    }

    private void add() {
        if(button_1.getText().equals("停止")){
            JOptionPane.showMessageDialog(null, "请先停止");
            return;
        }
        int selectedIndex = comboBox_hwnd.getSelectedIndex();
        if (selectedIndex == -1) return;
        Integer keyNum = ViewGet.comboBox(comboBox_key, "keyNum", Integer.class);
        List<Com> comList = ComPool.getComList();
        Com com = comList.get(selectedIndex);
        String intervalStr = ViewGet.textField(textField_interval);
        Integer interval = !intervalStr.matches("[0-9]+") ? 0 : Integer.valueOf(intervalStr);
        baseDataList.add(new BaseData(com.getHwnd(), keyNum, interval));
        initData();
    }

    public void initFrm() {
        List<Com> comList = ComPool.getComList();
        List<String> accountList = ComPool.getAccountList();
        comboBox_hwnd.removeAllItems();
        comboBox_key.removeAllItems();
        for (int i = 0; i < comList.size(); i++) {
            Hwnd hwnd = new Hwnd();
            hwnd.setHwnd(comList.get(i).getHwnd());
            hwnd.setAccount(accountList.get(i));
            comboBox_hwnd.addItem(hwnd);
        }
        for (BaseKey baseKey : BaseKey.values()) {
            comboBox_key.addItem(baseKey);
        }
    }

    private void initData() {
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);
        for (BaseData baseData : baseDataList) {
            Vector vector = new Vector();
            vector.add(baseData.getHwnd());
            vector.add(BaseKey.getNameByKeyNum(baseData.getKeyNum()));
            vector.add(baseData.getInterval());
            tableModel.addRow(vector);
        }
    }

    @AllArgsConstructor
    @Data
    class BaseData {
        private Integer hwnd;
        private Integer keyNum;
        private Integer interval;
    }
}
